import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.thrift.TException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class HiveMetaApp {

    //HiveMetaStore的客户端
    private HiveMetaStoreClient hiveMetaStoreClient;

    /**
     * 功能描述:
     * 设置HiveJDBC的数据源
     */
    @Before
    public void setHiveMetaStoreConf() {
        System.setProperty("hadoop.home.dir", "C:\\hadoop");
        HiveConf hiveConf = new HiveConf();
        //<name>hive.metastore.uris</name>
        //    <value>thrift://bdptest1:9083</value>
        hiveConf.set("hive.metastore.uris", "thrift://bdptest1:9083");
        try {
            //设置hiveMetaStore服务的地址
            this.hiveMetaStoreClient = new HiveMetaStoreClient(hiveConf);
            //当前版本2.3.4与集群3.0版本不兼容，加入此设置
           // this.hiveMetaStoreClient.setMetaConf("hive.metastore.client.capability.check", "false");
        } catch (MetaException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        }
    }
    // 由数据库的名称获取数据库的对象(一些基本信息)

    @Test
    public void getDBName() throws TException {

       Database database = this.hiveMetaStoreClient.getDatabase("prod_bd");
       // List<String> tablesList = this.hiveMetaStoreClient.getAllTables("prod_bd");
        System.out.println(database);

    }

    @Test
    public void getTablesOfDB() throws TException {

        //    Database database = this.hiveMetaStoreClient.getDatabase("");
        List<String> tablesList = this.hiveMetaStoreClient.getAllTables("prod_bd");
//        for (String tab : tablesList) {
//
//        }
        System.out.println(tablesList);

    }

    @Test
    public void getOneTable() throws TException {

        //    Database database = this.hiveMetaStoreClient.getDatabase("");
        Table table = this.hiveMetaStoreClient.getTable("default", "testuser");
//        for (String tab : tablesList) {
//
//        }
        System.out.println(table);
        System.out.println(table.getSd());
        System.out.println(table.getSd().getCols());
        System.out.println("分割info："+table.getSd().getSerdeInfo().getParameters());



    }

    // 根据数据库名称获取所有的表名
//    List<String> tablesList = this.hiveMetaStoreClient.getAllTables(dbName);
//    // 由表名和数据库名称获取table对象(能获取列、表信息)
//
//    Table table = this.hiveMetaStoreClient.getTable(dbName, tableName);
//    // 获取所有的列对象
//    List<FieldSchema> fieldSchemaList = table.getSd().getCols();
//
    // 关闭当前连接
    @After
    public void close() {

        this.hiveMetaStoreClient.close();
    }

}

